<script setup>
import {ShareIcon} from "tdesign-icons-vue-next";
import {onMounted, reactive, ref, computed} from "vue";
import {MessagePlugin} from 'tdesign-vue-next';
import error from "tdesign-icons-vue-next/lib/components/error.js";
import {currentAdministratorInfo, updateAdministratorPassword} from "@/api/administrator.js";
import {useAdministratorStore} from "@/stores/administrator.js";

const cover = 'https://tdesign.gtimg.com/site/source/card-demo.png';
const administratorStore = useAdministratorStore()

// 初始化页面信息 -------------------------------------------------------------------
const administratorInfo = reactive({
  id: 0,
  username: '',
  realName: '',
  gender: null,
  phone: '',
  email: '',
  university: '',
  parent: '',
  level: '',
});

onMounted(async () => {
  const res = await currentAdministratorInfo(administratorStore)
  administratorInfo.id = res.data.data.id
  administratorInfo.username = res.data.data.username
  administratorInfo.realName = res.data.data.realName
  administratorInfo.gender = res.data.data.gender
  administratorInfo.phone = res.data.data.phone
  administratorInfo.email = res.data.data.email
  administratorInfo.university = res.data.data.university
  administratorInfo.parent = res.data.data.parent
  administratorInfo.level = res.data.data.level
})
// 更新密码的弹窗 ----------------------------------------------------------------------
const passwordData = reactive({
  newPassword : '',
  checkPassword : ''
});


const visibleOverflowPassword = ref(false);
const closePassword = () => {
  visibleOverflowPassword.value = false;
};

const updateWindowPassword = () => {
  visibleOverflowPassword.value = true
}


const onValidate = ({ validateResult, firstError }) => {
  if (validateResult === true) {
    console.log('Validate Success');
  } else {
    console.log('Validate Errors: ', firstError, validateResult);
  }
};

const rePassword = (val) =>
    new Promise((resolve) => {
      const timer = setTimeout(() => {
        resolve(passwordData.newPassword === val);
        clearTimeout(timer);
      });
    });

const passwordValidator = (val) => {
  if (val.length > 0 && val.length <= 2) {
    return { result: false, message: '短', type: 'error' };
  }
  if (val.length > 2 && val.length <= 6) {
    return { result: false, message: '中', type: 'warning' };
  }
  return { result: true, message: '长', type: 'success' };
};

const passwordRule = {
  newPassword: [{ required: true, message: '密码必填', type: 'error' }, { validator: passwordValidator }],
  checkPassword: [
    // 自定义校验规则
    { required: true, message: '密码必填', type: 'error' },
    { validator: rePassword, message: '两次密码不一致' },
  ]

};

const changePassword = async ({e}) => {
  e.preventDefault();
  const res = await updateAdministratorPassword(administratorStore, passwordData.newPassword)
  if (res.data.code === 40000) await MessagePlugin.error("更新失败: " + res.data.description);
  else {
    await MessagePlugin.success("更新成功");
    visibleOverflowPassword.value = false;
  }
  // if (validateResult === true) {
  //   MessagePlugin.success('提交成功');
  // } else {
  //   console.log('Validate Errors: ', firstError, validateResult);
  //   MessagePlugin.warning(firstError);
  // }
};




const onReset = () => {
  MessagePlugin.success('重置成功');
};

</script>

<template>
  <t-layout style="height: 100%">
    <t-aside style="
      height: 100%;                /* 继承父容器高度 */
      display: flex;               /* 启用flex布局 */
      align-items: center;         /* 垂直居中 */
      justify-content: center;     /* 水平居中 */
      padding-left: 5%;
      padding-right: 5%;
      width: auto;
    ">
      <t-card :cover="cover" theme="poster2" :style="{ width: '400px' }" shadow>
        <template #footer>
          <t-comment avatar="https://tdesign.gtimg.com/site/avatar.jpg" :author="administratorInfo.realName"
                     :content="administratorInfo.university+' | '+administratorInfo.phone"/>
        </template>
        <template #actions>
          <!--          <t-dropdown :min-column-width="112" @click="clickHandler">-->
          <t-dropdown :min-column-width="112">
            <t-button variant="text" shape="square">
              <share-icon/>
            </t-button>
          </t-dropdown>
        </template>
      </t-card>
    </t-aside>
    <t-layout style="
      height: 100%;                /* 继承父容器高度 */
      display: flex;               /* 启用flex布局 */
      align-items: center;         /* 垂直居中 */
      justify-content: center;     /* 水平居中 */
      padding-left: 5%;
      padding-right: 5%;
      background-color: white;
      width: auto;">
      <t-descriptions title="个人信息">
        <t-descriptions-item label="用户名">{{ administratorInfo.username || '未设置' }}</t-descriptions-item>
        <t-descriptions-item label="真实姓名">{{ administratorInfo.realName || '未设置' }}</t-descriptions-item>
        <t-descriptions-item label="性别">
          {{
            administratorInfo.gender === 0 ? '男' : administratorInfo.gender === 1 ? '女' : '未设置'
          }}
        </t-descriptions-item>
        <t-descriptions-item label="电话号码">{{ administratorInfo.phone || '未设置' }}</t-descriptions-item>
        <t-descriptions-item label="邮箱">{{ administratorInfo.email || '未设置' }}</t-descriptions-item>
        <t-descriptions-item label="学校">{{ administratorInfo.university || '未设置' }}</t-descriptions-item>
        <t-descriptions-item label="签发人id">{{ administratorInfo.parent || '未设置' }}</t-descriptions-item>
        <t-descriptions-item label="权限等级">{{ administratorInfo.level}}</t-descriptions-item>
      </t-descriptions>
      <div style="display: flex; justify-content: flex-end; width: 100%; padding-top: 2%">
        <t-button theme="primary" @click="updateWindowPassword" style="margin-right: 3%">修改密码</t-button>
      </div>
    </t-layout>

  </t-layout>


  <t-dialog placement="center" header="修改密码" :footer="false" :visible="visibleOverflowPassword"
            :on-confirm="closePassword"
            :on-close="closePassword"
            width="30%">
    <t-divider/>
    <t-form ref="form" :data="passwordData" :rules="passwordRule" @reset="onReset" @submit="changePassword" @validate="onValidate" >

      <t-form-item label="密码" name="newPassword" help="密码建议大于6位">
        <t-input v-model="passwordData.newPassword" type="password"></t-input>
      </t-form-item>

      <t-form-item label="确认密码" name="checkPassword" help="再次输入密码">
        <t-input v-model="passwordData.checkPassword" type="password"></t-input>
      </t-form-item>

      <t-form-item>
        <t-space size="small">
          <t-button theme="primary" type="submit">提交</t-button>
          <t-button theme="default" variant="base" type="reset">重置</t-button>
        </t-space>
      </t-form-item>
    </t-form>
  </t-dialog>
</template>

<style scoped>

</style>